const commonjs = require('@rollup/plugin-commonjs')
const json = require('@rollup/plugin-json')
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const alias = require('@rollup/plugin-alias')
const ts = require('@rollup/plugin-typescript')
const esbuild = require('rollup-plugin-esbuild').default
const obfuscator = require('rollup-plugin-obfuscator').default
const dependencies = require('../package.json').dependencies

function servceConfig(env, { input, output, isMin = false }) {
  const isDev = env === 'development'

  const config = {
    // 入口文件
    input: input,
    output: {
      file: output,
      format: 'cjs'
    },
    plugins: [
      nodeResolve({ jsnext: true, preferBuiltins: true }), // 消除碰到 node.js 模块时⚠警告
      commonjs({
        sourceMap: false
      }),
      json(),
      // 语言支持
      ts({
        module: 'esnext'
      }),
      alias({
        entries: [{ find: '@', replacement: 'src' }]
      })
    ],
    // 指出应将哪些模块视为外部模块
    external: [
      'crypto',
      'assert',
      'fs',
      'util',
      'os',
      'events',
      'child_process',
      'http',
      'https',
      'path',
      ...Object.keys(dependencies)
    ]
  }

  if (!isDev && !isMin) {
    config.plugins.push(obfuscator({})) // 混淆代码
    config.plugins.push(
      esbuild({
        include: /\.[jt]s?$/, // default, inferred from `loaders` option
        exclude: /node_modules/,
        minify: !isDev,
        target: 'es2017', // default, or 'es20XX', 'esnext'
        define: {
          __VERSION__: '"x.y.z"'
        },
        // 添加额外的loader
        loaders: {
          //添加.json文件支持
          '.json': 'json'
        }
      })
    )
  }

  return config
}

module.exports = servceConfig
